package ch.ethz.fcl.metrobuzz.applications;

import java.awt.Color;
import java.io.File;

import javax.swing.JPanel;

import net.miginfocom.swing.MigLayout;

import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;

import ch.ethz.fcl.metrobuzz.MBContainer;
import ch.ethz.fcl.metrobuzz.MBProperty;
import ch.ethz.fcl.metrobuzz.controller.MBController;
import ch.ethz.fcl.metrobuzz.data.MBData;
import ch.ethz.fcl.metrobuzz.data.loader.plan.SingaporeTransitPlanFileLoader;
import ch.ethz.fcl.metrobuzz.render.MBRenderer;
import ch.ethz.fcl.metrobuzz.viewer.MBViewer;
import ch.ethz.fcl.metrobuzz.viewer.MBViewer.ProjectionType;

public class AccessibilityApp {
	private int screenWidth = 800;
	private int screenHeight = 600;

	public static int CANVAS_WIDTH = 1200,
			CANVAS_HEIGHT = (int) (CANVAS_WIDTH * 900.0F / 1440);
	private MBContainer container;

	public static void main(String[] args) {
		if (args.length != 0)
			new AccessibilityApp(args).run();
		else {
			String res = "res/Singapore/roadnetwork";
			File folder = new File(res);
			if (!folder.exists())
				res = "Singapore/roadnetwork";
			String[] arguments = { res };
			new AccessibilityApp(arguments).run();
		}
	}

	public AccessibilityApp(String[] args) {
		if (args.length == 0) {
			System.out.println("please specify data base path on command line");
			System.exit(0);
		}

		MBProperty.read("properties/accessibility_config.properties");
		container = new MBContainer();

		MBData data = new MBData(container);

		screenWidth = Display.getDesktopDisplayMode().getWidth();
		screenHeight = Display.getDesktopDisplayMode().getHeight();
		CANVAS_WIDTH = screenWidth - 300;
		CANVAS_HEIGHT = (int) (CANVAS_WIDTH * 900.0F / 1440);

		MBViewer view = new MBViewer(ProjectionType.Ortho, container);

		new MBRenderer(container);

		view.createDisplay(screenWidth, screenHeight, CANVAS_WIDTH,
				CANVAS_HEIGHT, "Accessibility Visualization");
		view.getCamera().initDistance(1.0f);
		view.getCamera().disablePan();

		JPanel panel = new JPanel(new MigLayout("fillx,ins 0", "", ""));
		panel.setBackground(Color.WHITE);
		panel.add(container.getRender().getAccessibilityRender()
				.getGlobalPanel(), "wrap");
		panel.add(container.getRender().getAccessibilityRender()
				.getLocalPanel(), "wrap, growx");
		panel.add(container.getRender().getAccessibilityRender()
				.getTimeScaledPanel(), "wrap, growx");
		view.getFrame().add(panel, "align 0px 0px");

		view.initFrame();

		new SingaporeTransitPlanFileLoader().load(data, args[0]);
		data.init();

		new MBController(container);

		container.createFont();
	}

	private void run() {
		while (!Display.isCloseRequested()) {
			GL11.glPushMatrix();
			container.getViewer().update();

			if (MBViewer.newUpdate) {
				container.getRender().render();
			}

			container.getControl().update();

			GL11.glPopMatrix();

			Display.update();
			Display.sync(32);
		}
		Display.destroy();
		System.exit(0);
	}
}
